//
//  BJCoinStoreViewController.m
//  BowJoy
//
//  Created by  on 2024/5/16.
//

#import "BJCoinStoreViewController.h"
#import "BJCoinStoreListCollectionViewCell.h"
#import "SCIAPManager.h"

@interface BJCoinStoreViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *myCoinLable;

@property (weak, nonatomic) IBOutlet UIView *bgGroundView;
@property (nonatomic) NSArray<BJGoodsSearchModelData *> *dataList;

@end

@implementation BJCoinStoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviTitle = @"Coin Shop";
    self.dataList = [NSArray array];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applePaySuccess) name:kNotificationAppleSuccessfulPurchase object:nil];////商品购买(支付)成功通知
    [[SCIAPManager sharedManager] startManager];

    [self initUI];
    [self requestMyCoin];
    [self getData];
    NSMutableArray *dataList = [NSMutableArray array];
    NSDictionary *dict = @{
        @"page":@"purchase",
        @"duration":@(0),
        @"event":@"pv",
        @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
    };
    [dataList addObject:dict];
    [[BJNetManager shareNetManager]postLogWithParam:dataList];
    
}
-(void)applePaySuccess{
    [self requestMyCoin];
}
-(void)requestMyCoin{
    kWeakSelf(weakSelf)

    [[BJNetManager shareNetManager]getUserCurrentCoinsWithcompletionHandler:^(BJUserCoinsModel * _Nonnull model, NSError * _Nonnull error) {
        if(!error){
            weakSelf.myCoinLable.text = [NSString stringWithFormat:@"%ld",(long)model.data.availableCoins];
        }
    }];
}


- (void)getData{
    [ASHUD showASLoading];
    [[BJNetManager shareNetManager] postSearchGoodsWithcompletionHandler:^(BJGoodsSearchModel * _Nonnull model, NSError * _Nonnull error) {
        [ASHUD hideHUD];
        if(!error && model.code == 0){
            self.dataList = model.data ;
            [self.collectionView reloadData];
        }
    }];

}


- (void)initUI{
    CGFloat itemW = (kScreenW - 20*2-10)/2;
    CGFloat itemH = itemW - 10;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(itemW, itemH);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing = 31;
    layout.minimumInteritemSpacing = 20;
    layout.sectionInset = UIEdgeInsetsMake(0, 24, 0, 24);
    
    UICollectionViewFlowLayout * layOut = [[UICollectionViewFlowLayout alloc]init];
    layOut.itemSize = CGSizeMake(itemW, itemH);
    self.collectionView.collectionViewLayout = layOut;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"BJCoinStoreListCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"BJCoinStoreListCollectionViewCell"];

}

#pragma mark --UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return  self.dataList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID=@"BJCoinStoreListCollectionViewCell";
    BJCoinStoreListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.model = self.dataList[indexPath.row];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    BJGoodsSearchModelData *model = self.dataList[indexPath.row];
    [ASHUD showASLoading];
    //创建订单接口
    [[BJNetManager shareNetManager] postCreateRechargeGoodsCode:model.code completionHandler:^(id  _Nonnull responOj, NSError * _Nonnull error) {
        if (!error){
            NSDictionary *dict = responOj;
            NSInteger code = [dict[@"code"] integerValue];
            if (code == 0){
                NSDictionary *dataDict = dict[@"data"];
                NSString *goodsCode = dataDict[@"goodsCode"];
                NSString *orderNo = dataDict[@"orderNo"];
                //走内购支付
                [SCIAPManager sharedManager].code = model.code;
                [[SCIAPManager sharedManager] requestProductWithId:goodsCode orderNo:orderNo price:[NSNumber numberWithFloat:model.price]];
                NSMutableArray *dataList = [NSMutableArray array];
                NSDictionary *dict = @{
                    @"page":@"createorder",
                    @"duration":@(0),
                    @"event":@"pv",
                    @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
                };
                [dataList addObject:dict];
                [[BJNetManager shareNetManager]postLogWithParam:dataList];
            }else{
                [ASHUD hideHUD];
                NSString *msg = dict[@"msg"];
                [ASHUD showWithText:msg afterDelay:1];
            }

        }
    }];

    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
